<?php

/**
 * 欧联关务(麦邦-集采报关系统对接)
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShopJiCai;
use App\Service\BaseService;
use App\Service\Code\Normal;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

class ShopJiCaiApiClient extends BaseService
{
    public $routers=[
        "orderCreate"       =>  "/api/pushOrders",
        "orderCancel"       =>  "/api/cancelOrders",
        "orderExpress"      =>  "/api/selectLogisticsno"
    ];
    protected $clientConfig;
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] )
    {
        $this->clientConfig = $apiBody;
    }

    /**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        $orderInfo      = $params['supplierOrder'];
        $orderItem      = $params['orderGoods'];
        $order          = $params['order'];
        $binfo          = $params['binfo'];
        //支付流水号
        $pay_sn         = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //优惠
        $discount_money = $orderInfo['discount_money'] < 0 ? - $orderInfo['discount_money'] : $orderInfo['discount_money'] ;
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //支付时间
        $pay_time       = date('Y-m-d H:i:s',$orderInfo['pay_time']);
        //支付流水号
        $pay_sn         = $order['paySerial'] ?? $orderInfo['pay_sn'];
        $order_sn       = $orderInfo['supplier_dsn'];
        
        //组装商品数据列表
        $goodsList          = [];
        $goodsTotalMoney    = 0;
        $way_tax_fee        = 0;
        foreach ($orderItem as $key =>  & $item )
        {
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            $price              = $item['price'];
            $spec_num           = $item['spec_num'];
            $quantity           = $item['quantity'];
            $supplier_skucode   = $item['supplier_skucode'];
            $goods_type         = $item['goods_type'];
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$quantity,3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney,(string)100,3);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100,3);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney,3);
            }
            
            //不含税价格
            $singleGoodsPrice       = bcdiv((string)$price, (string)$tax_rate,3);
            $singleGoodsPrice       = bcmul((string)$singleGoodsPrice,(string)100,3);
            $singleGoodsPrice       = bcdiv((string)ceil($singleGoodsPrice), (string)100,3);
            //商品总价
            $goodsTotalPrice        = bcmul((string)$singleGoodsPrice,(string)$quantity,3);
            
            //税费
            $tax                    = bcsub((string)$price,(string)$singleGoodsPrice,3);
            $taxAll                 = bcmul((string)$tax,(string)$quantity,3);
            
            //判断是不是保税订单
            $taxAll                 = $goods_type == 1 ? $taxAll : 0 ;
            $goodsInfo = [
                "itemId"      => $supplier_skucode,
                "itemName"    => $item['goods_name'],
                "price"       => (string)$singleGoodsPrice,
                "quantity"    => $quantity,
            ];
            $goodsList[] = $goodsInfo;
            $goodsTotalMoney    = bcadd((string)$goodsTotalMoney,(string)$goodsTotalPrice,3);
            $way_tax_fee        = bcadd((string)$way_tax_fee,(string)$taxAll,3); 
        }
        
        //订单总价（商品保税价格 + 运费）
        $deliver_money          = 0;
        $totalMoney             = bcadd((string)$goodsTotalMoney, (string)$deliver_money,3);
        $totalMoney             = bcadd((string)$totalMoney, (string)$way_tax_fee,3);
        
        //订单优惠金额
        $real_total_money       = $orderInfo['real_total_money'];
        $discount_money         = bcsub((string)$totalMoney,(string)$real_total_money,3);
        
        //判断商品类型
        $currentGoods           = current($orderItem);
        $way_tax_fee            = $currentGoods['goods_type'] == 1 ? $way_tax_fee : 0 ;
        
        //创建订单数据
        $data = [
            'orderNo'                   => $order_sn,
            "payTime"                   => date("Y-m-d H:i:s",$orderInfo['cd']),
            "acturalPaid"               => $real_total_money,
            "orderGoodTotal"            => $goodsTotalMoney,
            "Freight"                   => $deliver_money,
            "Discount"                  => $discount_money,
            "Tax"                       => $way_tax_fee,
            "BuyerRegno"                => $orderInfo['buyer_realname'],
            "buyTelephone"              => $orderInfo['recveive_phone'],
            "buyerName"                 => $orderInfo['buyer_realname'],
            'buyerIdNumber'             => $orderInfo['buyer_idcard'],
            'consignee'                 => $orderInfo['receive_name'],
            'consigneeIdNumber'         => $orderInfo['buyer_idcard'],
            'consigneeTelephone'        => $orderInfo['recveive_phone'],
            'consigneeProvince'         => $orderInfo['province'],
            'consigneeCity'             => $orderInfo['city'],
            'consigneeZone'             => $orderInfo['district'],
            'consigneeAddress'          => $orderInfo['receive_address'],
            'payCode'                   => $order['payCommanyCode']??$apply_extends['payCommanyCode'],
            "payNo"                     => $pay_sn,
            "note"                      => $order_sn,
        ];
        $requestParam = [
            'method'    => 'orderCreate',
            'data'      => [
                [
                    'Head'=>$data,
                    'Body'=>$goodsList
                ]
            ],
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 取消订单
     * @param array $param
     */
    public function orderCancel( $param = [] )
    {
        if( empty($param['supplierOrder']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder");
        }
        $requestParam = [
            'method'    => 'orderCancel',
            'data'      => [$param['supplierOrder']['supplier_dsn']],
        ];
        return $this->execute($requestParam);
    }
    
    
    /**
     * 获取发货物流信息
     */
    public function orderExpress( $param = [] )
    {
        if( empty($param['OrderNosReqs']) ) {
            return Normal::returnCode(Normal::FAIL,"except param OrderNosReqs");
        }
        $data = [
            "OrderNosReqs"  => $param['OrderNosReqs'],
        ];
        $requestParam = [
            'method'    => 'PostSynchro',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }
    


    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $method = $param['method'];
        $data  = [
            'User'=>[
                'userId'=>$this->clientConfig['userId'],
                'userKey'=>$this->clientConfig['userKey'],
            ],
            'Datas'=>$param['data']
        ];
        
        if( !isset($this->routers[$method]) ) {
            return Normal::returnCode(Normal::FAIL,"当前接口方法不存在{$method}");
        }
        
        $url = $this->clientConfig['baseurl'].$this->routers[$method];
        $parameter = [
            [
                'tag'       => 'Shopjicai_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'json',
                'header'    => [
                    "Content-Type: application/json",
                    "Accept:application/json",
                ],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $resHttp = json_decode($resTask['response']['result'], true);
        $resHttp = current($resHttp);
        if ($resHttp['code']==200){
            return Normal::returnCode(Normal::SUC,'操作成功',$resHttp);
        }
        $errorMsg = $resHttp['message']??'请求失败';
        return Normal::returnCode(Normal::FAIL,$errorMsg);
    }
}